package net.xdclass.config;

import com.amazonaws.ClientConfiguration;
import com.amazonaws.Protocol;
import com.amazonaws.auth.AWSCredentials;
import com.amazonaws.auth.AWSStaticCredentialsProvider;
import com.amazonaws.auth.BasicAWSCredentials;
import com.amazonaws.client.builder.AwsClientBuilder;
import com.amazonaws.regions.Regions;
import com.amazonaws.services.s3.AmazonS3;
import com.amazonaws.services.s3.AmazonS3ClientBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Component;

@Component
public class AmazonS3Config {

    @Autowired
    private MinioConfig minioConfig;

    @Bean(name = "amazonS3Client")
    public AmazonS3 getClient(){

        ClientConfiguration config = new ClientConfiguration();

        config.setProtocol(Protocol.HTTP);

        config.setConnectionTimeout(5000);
        config.setUseExpectContinue(true);

        //使用minio配置的秘钥创建访问凭证
        AWSCredentials awsCredentials = new BasicAWSCredentials(minioConfig.getAccessKey(),minioConfig.getAccessSecret());

        //设置Endopint
        AwsClientBuilder.EndpointConfiguration endpointConfiguration = new AwsClientBuilder.EndpointConfiguration(minioConfig.getEndpoint(), Regions.US_EAST_1.name());

        //使用上面的配置创建客户端
        return AmazonS3ClientBuilder.standard()
                .withClientConfiguration(config)
                .withCredentials(new AWSStaticCredentialsProvider(awsCredentials))
                .withEndpointConfiguration(endpointConfiguration)
                .withPathStyleAccessEnabled(true).build();


    }


}
